package pl.s7n.paint.edits;

import java.awt.Rectangle;

import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.UndoableEditSupport;

import pl.s7n.paint.DrawableCanvas;
import pl.s7n.paint.commands.AbstractStrokeCmd;
import pl.s7n.paint.commands.ResizeCmd;

public class ResizeEditManager extends AbstractEditManager<ResizeCmd> {

  private DrawableCanvas parent;

  public ResizeEditManager(UndoableEditSupport undoableEditSupport, DrawableCanvas parent) {
    super(undoableEditSupport);
    this.parent = parent;
  }

  public void editPerformed(ResizeCmd action) {
    undoableEditSupport.postEdit(new ResizeEdit(action));

    parent.setImage(action.getNewImage(), false);

    Rectangle clip = new Rectangle(0, 0, action.getNewImage().getWidth(), action.getNewImage().getHeight());
    for (AbstractStrokeCmd sa : parent.getDrawingEditManager().actions) {
      
      Rectangle saRect = sa.getRect();
      if (saRect == null) {
        sa.setRect(clip);
      } else {
        if (saRect.width > clip.width) {
          saRect.width = clip.width;
        }
        if (saRect.height > clip.height) {
          saRect.height = clip.height;
        }
      }
    }

    parent.redraw();
  }

  private class ResizeEdit extends AbstractUndoableEdit {
    private static final long serialVersionUID = 335755372811578290L;

    ResizeCmd                 newAction;

    public ResizeEdit(ResizeCmd newAction) {
      this.newAction = newAction;
    }

    @Override
    public String getRedoPresentationName() {
      return "Redo " + newAction.toString();
    }

    @Override
    public String getUndoPresentationName() {
      return "Undo " + newAction.toString();
    }

    @Override
    public void undo() {
      super.undo();
      parent.setImage(newAction.getOldImage(), false);
      parent.repaint();
    }

    @Override
    public void redo() {
      super.redo();
      parent.setImage(newAction.getNewImage(), false);
      parent.repaint();
    }
  }
}
